<template>
   <div class="analysis-container">
    <!-- 筛选条件卡片 -->
    <el-card class="filter-card" shadow="hover">
      <div class="filter-wrapper">
        <el-select
          filterable
          v-model="query.subId"
          placeholder="选择课程"
          class="course-select"
          @change="fetchData"
          clearable
          size="medium"
        >
          <el-option
            v-for="(item, index) in courseList"
            :key="index"
            :label="item.subName"
            :value="item.subId"
          />
        </el-select>
      </div>
    </el-card>

    <el-card :body-style="{position: 'relative'}">
    <div v-loading="loading" element-loading-text="数据加载中...">
    <!-- 图表容器 -->
    <div class="chart-group">
      <!-- 平均成绩图表 -->
      <el-card class="chart-card" shadow="hover">
        <div slot="header" class="card-header">
          <i class="el-icon-data-analysis"></i>
          <span>学期成绩对比分析</span>
        </div>
        <div ref="avgChart" class="chart-box"></div>
      </el-card>

      <!-- 及格率图表 -->
      <el-card class="chart-card" shadow="hover">
        <div slot="header" class="card-header">
          <i class="el-icon-pie-chart"></i>
          <span>学期及格率分析</span>
        </div>
        <div ref="passRateChart" class="chart-box"></div>
      </el-card>
    </div>
    </div>
    </el-card>
  </div>
  </template>
  
  <script>
  import * as echarts from 'echarts';
  import { getSub } from '@/api/txyStudentEvaluation';
  import { diffSemester } from '@/api/student'
  export default {
    data() {
      return {
        semesterData: [], // 后端返回的数据列表
        query:{
          subId:'',
        },
        courseList:[],
        loading: false,
      };
    },
    mounted() {
      this.initCourse();
    },
    methods: {
      initCourse(){
          getSub().then(res=>{
              this.courseList=res.data
          })
      },
      async fetchData() {
        try {
          this.loading = true
          const response = await diffSemester(this.query)
          this.semesterData = response.data
          this.$nextTick(() => this.initCharts())
        } catch (error) {
          this.$message.error('数据加载失败')
        } finally {
          this.loading = false
        }
      },
      initCharts() {
        // 提取学期名称作为横轴
        const semesters = this.semesterData.map(item => item.semester);
        
        // 初始化平均成绩图表
        const avgChart = echarts.init(this.$refs.avgChart);
        avgChart.setOption(this.getChartOption(
          '学期平均总成绩对比',
          '平均总成绩',
          semesters,
          this.semesterData.map(item => item.avgScore),
          '#5470c6' // 蓝色柱子
        ));
  
        // 初始化及格率图表
        const passRateChart = echarts.init(this.$refs.passRateChart);
        passRateChart.setOption(this.getChartOption(
          '学期及格率对比',
          '及格率 (%)',
          semesters,
          this.semesterData.map(item => item.passRate),
          '#91cc75' // 绿色柱子
        ));
  
        // 窗口缩放时自适应
        window.addEventListener('resize', () => {
          avgChart.resize();
          passRateChart.resize();
        });
      },
      getChartOption(title, yAxisName, semesters, data, color) {
        return {
          title: {
            text: title,
            left: 'center',
            textStyle: {
              fontSize: 16,
              color: '#303133'
            }
          },
          tooltip: {
            trigger: 'axis',
            backgroundColor: 'rgba(255,255,255,0.95)',
            borderWidth: 0,
            padding: 12,
            extraCssText: 'box-shadow: 0 4px 12px rgba(0,0,0,0.1);',
            formatter: params => {
              const value = params[0].value
              const suffix = yAxisName === '及格率 (%)' ? '%' : '分'
              return `
                <div style="font-size:14px;color:#606266">
                  <div style="font-weight:600;color:#409EFF;">${params[0].name}</div>
                  <div style="margin-top:8px;">
                    <span style="display:inline-block;width:8px;height:8px;background:${color};border-radius:50%;margin-right:8px;"></span>
                    ${params[0].seriesName}: 
                    <span style="font-weight:600;color:${color}">${value}${suffix}</span>
                  </div>
                </div>
              `
            }
          },
          xAxis: {
            type: 'category',
            data: semesters,
            axisLine: {
              lineStyle: {
                color: '#DCDFE6'
              }
            },
            axisLabel: {
              rotate: 45,
              fontSize: 12,
              color: '#606266'
            }
          },
          yAxis: {
            type: 'value',
            name: yAxisName,
            nameTextStyle: {
              color: '#909399'
            },
            splitLine: {
              lineStyle: {
                type: 'dashed'
              }
            },
            axisLabel: {
              color: '#909399',
              formatter: yAxisName === '及格率 (%)' ? '{value}%' : '{value}'
            }
          },
          series: [{
            name: yAxisName,
            type: 'bar',
            data: data,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: color },
                { offset: 1, color: this.lightenColor(color, 30) }
              ]),
              borderRadius: [4, 4, 0, 0]
            },
            barWidth: '60%',
            label: {
              show: true,
              position: 'top',
              color: '#606266',
              formatter: yAxisName === '及格率 (%)' ? '{c}%' : '{c}'
            }
          }]
        }
      },
      lightenColor(hex, percent) {
        // 颜色渐变处理函数
        const num = parseInt(hex.replace('#',''))
        const amt = Math.round(2.55 * percent)
        const R = (num >> 16) + amt
        const G = (num >> 8 & 0x00FF) + amt
        const B = (num & 0x0000FF) + amt
        return `#${(1 << 24 | (R<255?R<1?0:R:255) << 16 | (G<255?G<1?0:G:255) << 8 | (B<255?B<1?0:B:255)).toString(16).slice(1)}`
      }
    },

  }
  </script>
  <style scoped>
.analysis-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.filter-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.filter-wrapper {
  padding: 10px;
}

.course-select {
  width: 300px;
}

.chart-group {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(600px, 1fr));
  gap: 20px;
}

.chart-card {
  border-radius: 8px;
  overflow: hidden;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px 24px;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border-bottom: 1px solid #ebeef5;
}

.card-header i {
  font-size: 20px;
  color: #409EFF;
}

.card-header span {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.chart-box {
  width: 100%;
  height: 400px;
  padding: 15px;
}

@media (max-width: 768px) {
  .chart-group {
    grid-template-columns: 1fr;
  }
  
  .course-select {
    width: 100%;
  }
  
  .chart-box {
    height: 300px;
  }
  
  .card-header {
    padding: 12px;
  }
  
  .card-header i {
    font-size: 18px;
  }
}
</style>